var BSTYUN = BSTYUN || {};
BSTYUN.check = {
    isPhone: function(){
        var ua = navigator.userAgent.toLowerCase(),
            reg = /iPhone|iPad|Android|ucweb|windows\s+mobile|Windows\s+Phone/i;
            return reg.test(ua);
    },
    //IE6判定
    isIE6: window.VBArray && !window.XMLHttpRequest,
    //判断是否为中英文，数字，下划线，减号
    isNick: function(str) {
        var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
        return nickReg.test(str);
    },
    //判断邮箱
    isEmail: function(str) {
        var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
        return emailReg.test(str);
    },
    //判断手机
    isMobile: function(str) {
        var mobileReg = /^1[345678][0-9]{9}$/;
        return mobileReg.test(str);
    },
    // 判断固话
    isTelephone: function(str) {
        var phoneReg = /^0\d{2,3}-\d{5,9}$/;
        return phoneReg.test(str);
    },
    //判断URL
    isUrl: function(str) {
        var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
        return urlReg.test(str);
    },
    //判断数字
    isNum: function(str) {
        var numReg = /^[0-9]\d*$/;
        return numReg.test(str);
    },
    //是否传真
    isFax: function(str){
    	var faxReg = /^0\d{2,3}-\d{5,9}$/;
    	return faxReg.test(str);
    }
};
$(function(){
	init();//页面初始化
	/*表单验证*/
	BSTYUN.basicInfo.init();
})

BSTYUN.basicInfo = {
	flag: {
		realName: false,
		sex: true,
		birthday: false,
		phone: true,
		fixationTel: true,
		personEmail: true,
		fax: true,
		province: true,
		city: true,
		address: true,
		belongCompanyName: true,
		industry: true,
		scale: true,
		companyPosition: true
	},
	init: function(){
		var that = this;
		/*表单修改提交验证*/
		that.formcheck();
		/*失去焦点验证*/
		that.blurFocus();
	},
	formcheck: function(){
		var that = this,
			flag = {},
			$submit = $("#button"),
			$form = $("#personForm"),
			$inputs = $form.find("input[type='text']");
		$submit.on('click', function(event) {
			$.ajax({
				type : "POST",
				url : "/common/checkLogin",
				async : false,
				dataType: 'json',
				success:function(data) {
					if(data) {
						$.each($inputs,function(index, el) {
							var $this = $(this);
							$this.trigger('blur');
						});
						flag = that.flag;
						if(flag.realName && flag.sex && flag.birthday && flag.phone && flag.fixationTel 
							&& flag.personEmail && flag.fax && flag.province && flag.city && flag.address 
							&& flag.belongCompanyName && flag.industry && flag.scale && flag.companyPosition){
							//如果是普元个人帐号登录
							if(accountType=="2"){
								$("#companyIndustryId").removeAttr("disabled");
								$("#companyScaleId").removeAttr("disabled");
							}
							var personData = {};
							personData.realName = $("#realName").val();
							personData.sex = $('input[name="sex"]:checked').val()
							personData.birthday = $("#birthday").val();
							personData.phone = $("#phone").val();
							personData.fixationTel = $("#fixationTel").val();
							personData.personEmail = $("#personEmail").val();
							personData.fax = $("#fax").val();
							personData.provinceCode = $("#provinceCode").val();
							personData.cityCode = $("#cname").val();
							personData.areaCode = $("#area").val();
							personData.address = $("#address").val();
							personData.belongCompanyName = $("#belongCompanyName").val();
							personData.companyIndustryId = $("#companyIndustryId").val();
							personData.companyScaleId = $("#companyScaleId").val();
							personData.companyPosition = $("#companyPosition").val();
							$.ajax({
						        cache: true,
						        type: "POST",
						        url:"/user/userCenter/update/basicInfo?random="+Math.random(),
						        data: personData,// 你的formid
						        dataType:'json',
						        async: true,
						        error: function(request) {
						        	BSTYUN.dialog.warn("提交失败，请联系客服");
						        },
						        success: function(data) {
						        	if(data==true){
						        		BSTYUN.dialog.ok("保存成功");
						        		return true;
						        	}else{
						        		BSTYUN.dialog.warn("保存失败");
						        		return false;
						        	}
						        }
						    });
						}
					}else {
						location.href = "/user/login?returnUrl="+requestURI;
					}
				}
			})
		});
	},
	blurFocus: function(){
		var that = this,
			$form = $("#personForm"),
			$inputs = $form.find("input[type='text']");
		$form.on('blur', "input[type='text']", function(event) {
			var $this = $(this),
				name = $this.attr('name'),
				value = $.trim($this.val());
			switch (name){
				case 'realName':
					if (value == '' || value.length == 0) {
						that.showError($this);
					}else{
						if(value.length <= 10){
							that.clearError($this);
						}else{
							that.showError($this,'最大地址长度为10个字符');
						}
					}
					break;
				case 'birthday':
					if (value == '' || value.length == 0) {
						that.showError($this);
					}else{
						that.clearError($this);
					}
					break;
				case 'phone':
					if (value == '' || value.length == 0) {
					}else{
						if(BSTYUN.check.isMobile(value)){
							that.clearError($this);
						}else{
							that.showError($this,'请输入正确的手机号');
						}
					}
					break;
				case 'fixationTel':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 12){
							if(BSTYUN.check.isTelephone(value)){
								that.clearError($this);
							}else{
								that.showError($this,'请输入正确的固定电话(格式，区号-号码)');
							}
						}else{
							that.showError($this,'最大地址长度为12个字符');
						}
						
					}
					break;
				case 'personEmail':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 30){
							if(BSTYUN.check.isEmail(value)){
								that.clearError($this);
							}else{
								that.showError($this,'请输入正确的电子邮件地址');
							}
						}else{
							that.showError($this,'最大地址长度为30个字符');
						}
					}
					break;
				case 'fax':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 12){
							if(BSTYUN.check.isFax(value)){
								that.clearError($this);
							}else{
								that.showError($this,'请输入正确的传真号码(格式，区号-号码)');
							}
						}else{
							that.showError($this,'最大地址长度为12个字符');
						}
					}
					break;
				case 'address':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 50){
							that.clearError($this);
						}else{
							that.showError($this,'最大地址长度为50个字符');
						}
					}
					break;
				case 'belongCompanyName':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 50){
							that.clearError($this);
						}else{
							that.showError($this,'最大公司长度为50个字符');
						}
					}
					break;
				case 'companyPosition':
					if (value == '' || value.length == 0) {
					}else{
						if(value.length <= 20){
							that.clearError($this);
						}else{
							that.showError($this,'最大职位长度为20个字符');
						}
					}
					break;
			};
		}).on('focus', "input[type='text']", function(event) {
			var $this = $(this);
			that.clearError($this);
		});;

	},
	/*显示错误信息*/
	showError: function($elem,str){
		var that= this,
			name = $elem.attr('name');
		switch (name){
			case 'realName':
				str = str === undefined ? '姓名不能为空' : str;
				appendError($elem,str);
				that.flag.realName = false;
				break;
			case 'birthday':
				str = str === undefined ? '出生日期不能为空' : str;
				appendError($elem,str);
				that.flag.birthday = false;
				break;
			case 'phone':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.phone = false;
				break;
			case 'fixationTel':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.fixationTel = false;
				break;
			case 'personEmail':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.personEmail = false;
				break;
			case 'fax':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.fax = false;
				break;
			case 'address':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.address = false;
				break;
			case 'belongCompanyName':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.belongCompanyName = false;
				break;
			case 'companyPosition':
				str = str === undefined ? '' : str;
				appendError($elem,str);
				that.flag.companyPosition = false;
				break;
		};
		function appendError($elem,str){
			var $next = $elem.nextAll('.errormsg');
			if ($next.size() > 0) {
				$next.html(str);
			}else{
				var html = '<span class="errormsg" >'+str+'</span>';
				$elem.after(html);
			}
		}
	},
	/*清除错误信息*/
	clearError: function($elem){
		var that= this,
			name = $elem.attr('name');
		switch (name){
			case 'realName':
				that.flag.realName = true;
				break;
			case 'birthday':
				that.flag.birthday = true;
				break;
			case 'phone':
				that.flag.phone = true;
				break;
			case 'fixationTel':
				that.flag.fixationTel = true;
				break;
			case 'personEmail':
				that.flag.personEmail = true;
				break;
			case 'fax':
				that.flag.fax = true;
				break;
			case 'address':
				that.flag.address = true;
				break;
			case 'belongCompanyName':
				that.flag.belongCompanyName = true;
				break;
			case 'companyPosition':
				that.flag.companyPosition = true;
				break;
		};
//		$elem.nextAll('.errormsg').empty();
		$elem.nextAll('.errormsg').remove();
	}
}
//全局弹窗
/*BSTYUN.dialog = {
	    close: function (id) {
	        var i,list = $.dialog.list;
	        if(id){
	            list[id].close();
	        }else{
	            for (i in list) {
	                list[i].close();
	            }
	        }
	    },
	    creat: function (options) {
	        var dialog = null;
	        options = $.extend({
	            fixed:true,
	            title:false,
	            lock:true,
	            padding:'20px 40px',
	            id: '',
	            content: ''
	        },options);
	        dialog=$.dialog(options);
	        return dialog;
	    },
	    success: function (html,time) {
	        var dialog = null;
	        time = time || 2;
	        this.close();
	        html = '<div class="success-tip"><i class="iconfont">&#379;</i>'+html+'</div>'
	        dialog = this.creat({id:'success',content:html,lock:false});
	        setTimeout(function(){
	            var $dg = $(dialog.DOM.wrap);
	            $dg.animate({'top':'-=50px','opacity':0},300,'easeInBack',function(){
	                dialog.close();
	            });
	        }, time*1000);
	    },
	    warn: function (html,callback){
	        var dialog = null;
	        html = '<div class="warn-tip"><i class="iconfont">&#227;</i>'+html+'</div>';
	        dialog = this.creat({id:'warn',content:html});
	        dialog.button({
	            name: '知道了',
	            focus: true,
	            callback: callback
	        });
	    },
	    ok: function (html,callback){
	        var dialog = null;
	        html = '<div class="ok-tip"><i class="iconfont">&#379;</i>'+html+'</div>';
	        dialog = this.creat({id:'ok',content:html});
	        dialog.button({
	            name: '知道了',
	            focus: true,
	            callback: callback
	        });
	    },
	    confirm: function (html,callback) {
	        var dialog = null;
	        html = '<div class="confirm-tip"><i class="iconfont">&#228;</i>'+html+'</div>';
	        dialog = this.creat({id:'confirm',content:html});
	        dialog.button({
	            name: '确定',
	            focus: true,
	            callback: callback
	        },{
	            name: '取消'
	        });
	    }
};*/
var accountType = null;
function init(){
	accountType = $("#isYun").val();
	if(accountType=="0"){
		$("#personForm").hide();
		$("#companyForm").show();
//		$("#belongCompanyName").attr("readonly","true");
//		$("#companyDomainName").attr("readonly","true");
//		$("#companyDepartmentId").attr("readonly","true");
//		$("#virtualPhone").attr("readonly","true");
	}else if(accountType=="2"){
		$("#personForm").show();
		$("#companyForm").hide();
		$("#belongCompanyName").attr("readonly","true");
		$("#companyIndustryId").attr("disabled","disabled");
		$("#companyScaleId").attr("disabled","disabled");
		$("#companyPosition").attr("readonly","true");
	}
	
	/**
	 * 判断性别
	 */
	var sex = $("#sex").val();
	if(sex=="0"){
		$("#Male").attr("checked","checked");
	}else if(sex=="1"){
		$("#Women").attr("checked","checked");
	}else{
		$("#Privacy").attr("checked","checked");
	}
}
/**
 *显示个人基本信息 
 */
//function showPerson(){
//	$("#personForm").show();
//	$("#companyForm").hide()
//}

/**
 *显示企业基本信息 
 */
//function showCompany(){
//	$("#companyForm").show()
//	$("#personForm").hide();
//}

/**
 * 基本信息提交
 */
//function personSubmit(){
//	$.ajax({
//		type : "POST",
//		url : "/common/checkLogin",
//		async : false,
//		dataType: 'json',
//		success:function(data) {
//			if(data) {
//				var personData = {};
//				personData.realName = $("#realName").val();
//				personData.sex = $('input[name="sex"]:checked').val()
//				personData.birthday = $("#birthday").val();
//				personData.phone = $("#phone").val();
//				personData.fixationTel = $("#fixationTel").val();
//				personData.personEmail = $("#personEmail").val();
//				personData.fax = $("#fax").val();
//				personData.provinceCode = $("#provinceCode").val();
//				personData.cityCode = $("#cname").val();
//				personData.address = $("#address").val();
//				personData.belongCompanyName = $("#belongCompanyName").val();
//				personData.companyIndustryId = $("#companyIndustryId").val();
//				personData.companyScaleId = $("#companyScaleId").val();
//				personData.companyPosition = $("#companyPosition").val();
//				$.ajax({
//			        cache: true,
//			        type: "POST",
//			        url:"/user/userCenter/update/basicInfo?random="+Math.random(),
//			        data: personData,// 你的formid
//			        dataType:'json',
//			        async: true,
//			        error: function(request) {
//			        	BSTYUN.dialog.warn("提交失败，请联系客服");
//			        },
//			        success: function(data) {
//			        	if(data==true){
//			        		BSTYUN.dialog.ok("保存成功");
//			        		return true;
//			        	}else{
//			        		BSTYUN.dialog.warn("保存失败");
//			        		return false;
//			        	}
//			        }
//			    });
//			}else {
//				location.href = "/user/login?returnUrl="+requestURI;
//			}
//		}
//	})
//
//}

//function companySubmit(){
//	$.ajax({
//		type : "POST",
//		url : "/common/checkLogin",
//		async : false,
//		dataType: 'json',
//		success:function(data) {
//			if(data) {	$.ajax({
//		        cache: true,
//		        type: "POST",
//		        url:"/user/userCenter/update/company",
//		        data:$('#companyForm').serialize(),// 你的formid
//		        async: true,
//		        error: function(request) {
//		        	BSTYUN.dialog.warn("提交失败，请联系客服");
//		        },
//		        success: function(data) {
//		        	if(data==true){
//		        		BSTYUN.dialog.ok("保存成功");
//		        	}else{
//		        		BSTYUN.dialog.warn("保存失败");
//		        	}
//		        }
//		    });}else {
//				location.href = "/user/login?returnUrl="+requestURI;
//			}
//		}
//	})
//}